package org.example.kaptcha.controller;

import com.google.code.kaptcha.Constants;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
@RequestMapping("/admin")
@RestController
public class KaptchaController {
    //设置时间问60s
    private final static long VALID_MILLIS_TIME = 60 * 1000;
    @RequestMapping("/check")
    public boolean checkHomeCaptcha(String captcha, HttpSession session) {
        if (!StringUtils.hasLength(captcha)) {
            return false;
        }
        //获取验证码
        String savedCaptcha = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);
        //获取验证生成时间
        Date sessionDate = (Date) session.getAttribute(Constants.KAPTCHA_SESSION_DATE);
        if (captcha.equalsIgnoreCase(savedCaptcha)) {
            if (sessionDate == null || System.currentTimeMillis() - sessionDate.getTime() < VALID_MILLIS_TIME)
                return true;
        }
        return false;
    }
}
